package com.zq.user.service.impl;

import cn.dev33.satoken.secure.SaSecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zq.common.mail.SendMailService;
import com.zq.user.dao.dto.PasswordDto;
import com.zq.user.dao.entity.Users;
import com.zq.user.service.IUsersService;
import com.zq.user.service.ResetPassword;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class ResetPasswordImpl implements ResetPassword {

    @Resource
    private SendMailService sendMailService;


    @Resource
    private RedisTemplate<String,String> redisTemplate;

    @Resource
    private IUsersService userService;


//    根据邮箱发送验证码
    @Override
    public void sendEmail(String email) {
        // 发送邮件
        String codeMail = sendMailService.sendCodeMail(email);
        log.info("codeMail:{}",codeMail);
//        将验证码存入redis
        redisTemplate.opsForValue().set("user"+email,codeMail,5, TimeUnit.MINUTES);






    }

//    检验验证码
    @Override
    public void sendCode(String code,String email) {
        String redisCode = redisTemplate.opsForValue().get("user"+email);
if(redisCode==null){
    throw new RuntimeException("验证码已过期");
}
log.info("redisCode:{}",redisCode);
log.info("code:{}",code);
if(!redisCode.equals(code)){
    throw new RuntimeException("验证码错误");
}

        // 验证码正确，删除redis中的验证码
        redisTemplate.delete(email);
    }

//    重置密码
    @Override
    public void sendPassword(PasswordDto passwordDto) {
        Users user = userService.getOne(new LambdaQueryWrapper<Users>().eq(passwordDto.getEmail()!=null,Users::getEmail, passwordDto.getEmail()));
        String md5 = SaSecureUtil.md5(passwordDto.getPassword());
        if(md5.equals(user.getPassword())){
            throw new RuntimeException("新密码不能与旧密码相同");
        }
//        修改密码
        user.setPassword(md5);
        userService.updateById(user);
        log.info("重置密码成功");
    }


}
